import { defineStore } from "pinia";
import { useOtherStore } from "./other-store";
// import { mande } from "mande";
interface UserInfo {
  name: string;
  age: number;
  id: number;
  active?: boolean;
}
interface State {
  userList: UserInfo[];
  user: UserInfo | null;
  count: number;
  age: number;
  localData: number;
}
// 应用通信
export const appCommu = defineStore("appCommu", {
  // state: () => ({ count: 0, name: "Eduardo" }),
  state: (): State => {
    return {
      userList: [],
      user: null,
      count: 3,
      age: 12,
      localData: 22,
    };
  },
  getters: {
    doubleCount: (state) => state.count * 2,
    sqrtCount: (state) => Math.sqrt(state.count),
    // the return type **must** be explicitly set
    doublePlusOne(): number {
      // autocompletion and typings for the whole store ✨
      return this.doubleCount + 1;
    },
    // Passing arguments to getters
    getUserByObj: (state) => {
      return (userId: number): any =>
        state.userList.find((user) => user.id === userId);
    },
    getUserById: (state) => {
      return (userId: number): any =>
        state.userList.findIndex((user) => user.id === userId);
    },
    getActiveUserById(state) {
      const activeUsers = state.userList.filter((user) => user.active);
      return (userId: number) => activeUsers.find((user) => user.id === userId);
    },
    // Accessing other stores getters
    otherGetter(state) {
      const otherStore = useOtherStore();
      return state.localData + otherStore.data;
    },
  },
  actions: {
    increment() {
      this.count++;
    },
    randomizeCounter() {
      this.count = Math.round(100 * Math.random());
    },
  },
});
